package com.huzz.util;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.io.IOException;
import java.util.*;

/**
 * 权限获取反序列化
 *
 * @author Huzz
 * @create 2022-08-23 17:57
 */
public class JackAuthorityDeserializer extends JsonDeserializer {

    @Override
    public Collection<? extends GrantedAuthority> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
        if (jsonParser == null || jsonParser.getText() == null) {
            return null;
        }
        List<Map<String, String>> mapList = jsonParser.readValueAs(List.class);

        Optional.ofNullable(mapList).orElse(Collections.emptyList()).forEach(e -> authorities.add(new SimpleGrantedAuthority(e.get("authority"))));

        return authorities;
    }
}
